import axios from 'axios'
import qs from 'qs'
import store from '../store/index'
import {Message} from 'element-ui'
import router from '../router/index'
import common from "./common";

const config = {
  appID: 'wx00f298f904171368',
  appsecret: '69ac009d69e8030edd26a6b590a341c6'
}

// axios.defaults.timeout = 5000
axios.defaults.headers.post['Content-Type'] = 'application/json'
// axios.defaults.withCredentials=true
// axios.defaults.crossDomain=true

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
  let url = config.url
  if (url.includes('GhPush')) {//微信接口
    config.baseURL = window.global.wxServerURL
  } else {
    let token = sessionStorage.getItem('webToken')
    if (token && url != '/User/Login_App') config.headers.token = token
    // config.baseURL = 'http://115.29.230.26:8800'
    config.baseURL = store.state.comm.serverURL
  }
  return config
}, function (error) {
  return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use(function (res) {
  if(res.data.CmdState!=undefined||store.state.user.operatePwd){
    return Promise.resolve(res.data)
  }else{//通讯提示
    if (isHttpSuccess(res.data)) {
      return Promise.resolve(res.data)
    }else{
      return Promise.reject()
    }
  }
}, function (error) {
  let status = error.response&&error.response.status
  if (status == '401') {
    sessionStorage.removeItem('userInfo')
    sessionStorage.removeItem('token')
    router.push('/login')
  } else if (status == '403') {
    // store.commit('user/SET_USER_PWD', '')
    Message({showClose: true, message: error.response.data, type: 'error'})
  } else if (status == '402') {
    Message({showClose: true, message: error.response.data, type: 'error'})
  }else{
    Message({showClose: true, message: '请求错误：'+error.request.responseURL,type: 'error',duration:5000})
  }
  return Promise.reject(error)
});

const errorCode={1:'未登录',2:'用户不存在',3:'密码不正确',4:'验证码不正确',5:'验证码不准确',6:'无权限',
  7:'设备已存在',8:'用户禁用',9:'session丢失',10:'读取系统参数失败',11:'超时',12:"解析JSON出错",13:'参数不正确',
  14:'设备不在线',15:'命令请求不支持',16:'解析应答帧出问题',17:'应答否认',18:'文件校验错误',19:'设备不存在',20:'设备地址格式错误',
  21:'数据超范围',31:'nb deviceId不存在',32:'nb deviceId不存在'
}
export default {
  config,
  errorCode,
  fetch(url, params) {
    return new Promise((resolve, reject) => {
      axios.post(url, params).then(response => {
        if (response != undefined) resolve(response)
      }, err => {
      }).catch((error) => {
        reject(error)
      })
    })
  },
  fetchSimple(url, params) {
    return new Promise((resolve, reject) => {
      axios.post(url, qs.stringify(params), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
        .then(response => {
          // if (response != undefined) resolve(response)
          resolve(response != undefined ? response : '')
        }, err => {
        }).catch((error) => {
          reject(error)
        })
    })
  },
  fetchAccessToken() {
    var instance = axios.create({
      baseURL: 'https://open.ys7.com/'
    });
    return new Promise((resolve, reject) => {
      instance.post('/api/lapp/token/get', qs.stringify({appKey: '9mqitppidgce4y8n54ranvyqc9fjtsrl&appSecret=096e76501644989b63ba0016ec5776'}), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
        .then(response => {
          resolve(response != undefined ? response : '')
        }, err => {
        }).catch((error) => {
        reject(error)
      })
    })
  },
  get(url, params) {
    if (!params) {
      params = {}
    }
    return new Promise((resolve, reject) => {
      axios.get(url, {params: params}).then(response => {
        if (response != undefined) resolve(response)
      }, err => {
        reject(err);
      }).catch((error) => {
        reject(error)
      })
    })
  },
  fetchFile(url, params) {
    return new Promise((resolve, reject) => {
      axios.post(url, qs.stringify(params),
        {headers: {'Content-Type': 'application/x-www-form-urlencoded'}, responseType: 'arraybuffer'})
        .then(response => {
          resolve(response != undefined ? response : '')
        }, err => {
        }).catch((error) => {
          reject(error)
        })
    })
  },
  httpFormData(url, params) {
    //'multipart/form-data' application/json
    let config = {
      headers: {'Content-Type': 'multipart/form-data'}
    }
    return new Promise((resolve, reject) => {
      axios.post(url, params, config).then(response => {
        resolve(response);
      }, err => {
        reject(err);
      }).catch((error) => {
        reject(error)
      })
    })
  },
  ajaxPost(o, callback) {
    let token = store.state.user.token
    $.ajax({
      url: o.url,
      data: o.data,
      cache: false,
      contentType: false,
      processData: false,
      type: 'post',
      headers: {'token': token},
      xhrFields: {withCredentials: true},
      success: function(r) {
        if (r.err) {
          return Message.error(r.err)
        } else {
          callback(r.data);
        }
      },
      error: function() {}
    });
  },
  formatDate:common.formatDate,
}

let isHttpSuccess=function(r) {
  var state=r.err?-1:0;
  if (r.CmdState != undefined) {
    state = r.CmdState
  } else {
    state = r.state||state
  }
  if (state == 0) {
    return true
  } else if (state == -1) {
    Message({showClose: true, message: (r.err || '系统错误！'), type: 'error'})
    return false
  } else if (state == 1) {
    sessionStorage.removeItem('userInfo')
    sessionStorage.removeItem('token')
    router.push('/login')
    Message({showClose: true, message: '系统未登录！', type: 'error'})
    return false
  } else {
    Message({showClose: true, message:r.err||errorCode[state], type: 'error'})
    return false
  }
}
